import { createApp } from 'vue'
import App from './App.vue'
import router from "./router"
import request from './services/request'
import tools from './services/tools'
import VueCookies from 'vue-cookies'


// 引入vant
import vant from "vant"
import { Lazyload } from 'vant';
import 'vant/lib/index.css'


let app = createApp(App)
        // .provide('$tools',tools)
        .use(vant)
        .use(router)
        .use(request)
        .use(tools)
        .use(VueCookies)
        .use(Lazyload)
        .mount('#app')


// //全局路由前置守卫
router.beforeEach(async(to,from,next)=>{
        // 判断是否需要登录
        const login = to.meta.login?to.meta.login:""
        let business = app.$cookies.get("business")?app.$cookies.get("business"):{}
        // 需要登录
        if(login){
                // 判断business是否为空
                if(typeof business !== "object" || Object.getOwnPropertyNames(business).length == 0){
                        app.$cookies.remove("business")
                        console.log(2)
                        next("/business/login");
                        return false
                }
                // 判断cookie
                let id = business.id?business.id:""
                let mobile = business.mobile?business.mobile:""
                if(!id || !mobile){
                        // 没有id或者手机号
                        next("/business/login");
                        return false
                }else{
                        // 发送请求，判断是否非法登录
                        let result = await app.$POST({
                                url:"business/check",
                                params:{
                                        id,
                                        mobile
                                }
                        })
                        if(result.code){
                                next()   
                                return false
                        }else{
                                // 删除cookie
                                app.$cookies.remove("business")
                                next(result.url)
                                return false
                        }
                }
        }else{
                // 不需要登录
                // 判断是否是登录界面
                if(to.name === "login" || to.name === "register"){
                        // 判断是否有cookie
                        if(business.id && business.mobile){
                                next(from.path)
                                return false
                        }else{
                                next()
                                return false
                        }
                }
                next()
                return false
        }
})